package com.example.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author Jiange
 * @create 2021-05-07-16:16
 */
@Controller
public class MyController {
    @GetMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/form")
    public String form(String username, String password, Model model){
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
            Subject subject1 = SecurityUtils.getSubject();

            Session session = subject1.getSession();

            session.setAttribute("name",username);
            System.out.println(subject1.isRemembered());
            return "redirect:/vip1";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("mes","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("mes","密码错误");
            return "login";
        }
    }

    @GetMapping("/vip1")
    public String vip1(){
        return "vip1";
    }
}
